package com.xilihui.xlh.business.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.activitys.MergePaymentsActivity;
import com.xilihui.xlh.business.activitys.StartAppointmentActivity;
import com.xilihui.xlh.business.activitys.TakeGoodsActivity;
import com.xilihui.xlh.business.adapters.MyAppointmentAdapter;
import com.xilihui.xlh.business.entities.AppointmentEntity;
import com.xilihui.xlh.business.requests.MyAppointmentRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.constant.StrConst;
import com.xilihui.xlh.core.app.BaseCompatFragment;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.exception.DefaultExceptionListener;
import com.xilihui.xlh.core.exception.ExceptionManager;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.feezu.liuli.timeselector.Utils.TextUtil;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/6/21.
 */

public class WeAppointmentFragment extends BaseCompatFragment implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {

    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.rl_fukuang)
    RelativeLayout rl_fukuang;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.tv_orderNum)
    TextView tv_orderNum;
    @BindView(R.id.tv_hebinfukuang)
    TextView tv_hebinfukuang;
    
    int page = 1;
    int status = 0;
    boolean isAll = false;//是否全选  默认没有
    
    ExceptionManager exceptionManager;
    MyAppointmentAdapter myAppointmentAdapter;
    
    BaseAdapter<AppointmentEntity.DataBean.AppointBean> baseAdapter;
    ArrayList<AppointmentEntity.DataBean.AppointBean> appointDatas = new ArrayList<>();
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_apponitment,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getExtras();
        YEventBuses.register(this);
        if(status==2){
            rl_fukuang.setVisibility(View.VISIBLE);
        }else {
            rl_fukuang.setVisibility(View.GONE);
        }
        
        exceptionManager = new ExceptionManager(smartRefreshLayout,new DefaultExceptionListener(this)){
            @Override
            protected int getEmptyView() {
                return R.layout.empty_order;
            }
        };
        
        exceptionManager.hide();
        
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        
        myAppointmentAdapter = new MyAppointmentAdapter(getActivity(),status);
        recyclerView.setAdapter(myAppointmentAdapter);
        
        getData(true,page);
        
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(isAll){
                    tv_orderNum.setText("合计："+myAppointmentAdapter.getSelect().size()+"个预约单");
                    isAll = false;
                }else {
                    myAppointmentAdapter.isAllSelectOrCancel(b);
                    tv_orderNum.setText("合计："+myAppointmentAdapter.getSelect().size()+"个预约单");
                }
                
            }
        });
        
    }

    private void getExtras() {
        status = getArguments().getInt(StrConst.MY_APPOINT_TYPE, 0);
    }
    
    public void getData(boolean isLoading, final int page){
        
        if(status==0&&page==1){
            isLoading = true;
        }else {
            isLoading = false;
        }
        
        MyAppointmentRequest.myAppointment(getContext(),status,page)
                            .compose(DoTransform.<AppointmentEntity>applyScheduler(getActivity(),isLoading))
                            .compose(WeAppointmentFragment.this.<AppointmentEntity>bindToLifecycle())
                            .subscribe(new HttpSubscriber<AppointmentEntity>(getActivity()) {
                                @Override
                                protected void onSuccess(AppointmentEntity entity) {
                                    
                                    if(page==1){
                                        appointDatas.clear();
                                        int num = entity.getData().getAppoint().size();
                                        
                                        int num1 = 0;
                                        if(status==2){
                                            num1 = entity.getData().getServerAccount().size();
                                        }
                                        if(num<1&&num1<1){
                                            exceptionManager.showEmpty();
                                        }else {
                                            exceptionManager.hide();
                                        }
                                        
                                        if(num<1){
                                            checkBox.setVisibility(View.INVISIBLE);
                                        }
                                        
                                    }
                                    
                                    smartRefreshLayout.finishRefresh();
                                    smartRefreshLayout.finishLoadMore();
                                    
                                    ArrayList<AppointmentEntity.DataBean.AppointBean> skData =
                                            (ArrayList<AppointmentEntity.DataBean.AppointBean>) entity.getData().getServerAccount();
                                    
                                    if(skData!=null&&skData.size()>0){
                                        for (int i=0;i<skData.size();i++){
                                            skData.get(i).setType(2);
                                        }
                                        appointDatas.addAll(0,skData);
                                        LogUtil.i("mylog","正在收款数据");
                                    }
                                                                        
                                    appointDatas.addAll(entity.getData().getAppoint());
                                    LogUtil.i("mylog","datas:"+appointDatas.size());
                                    myAppointmentAdapter.setData(appointDatas); 
                                    
                                    if(entity.getPageCount()>=page){
                                        smartRefreshLayout.finishLoadMoreWithNoMoreData();
                                    }else {
                                        smartRefreshLayout.setNoMoreData(false);
                                    }
                                    
                                }
                                
                                @Override
                                protected void onFail(String msg) {
                                    ToastUtil.toastShortNegative(msg);
                                    smartRefreshLayout.finishRefresh();
                                    smartRefreshLayout.finishLoadMore();
                                }
                            });
        
    }
    
    public void showData(BaseViewHolder holder, AppointmentEntity.DataBean.AppointBean entity, int position){
        
        holder.setText(R.id.tv_shopName,entity.getAgent().getName());
        
        switch (0){
            case 0:
                holder.setText(R.id.tv_waitStart,"还未开始");
                break;
            case 1:
                holder.setText(R.id.tv_waitStart,"进行中");
                break;
            case 2:
                holder.setText(R.id.tv_waitStart,"做完但还未结账");
                break;
            case 3:
                holder.setText(R.id.tv_waitStart,"已结账完成 ");
                break;
            case 4:
                holder.setText(R.id.tv_waitStart,"已结账完成");
                break;
            case 5:
                holder.setText(R.id.tv_waitStart,"店取消");
                break;
        }
        
        holder.setText(R.id.iv_address,entity.getAgent().getAddress());
        holder.setText(R.id.tv_time,entity.getStart_time()+"~"+entity.getEnd_time());
        String type = entity.getHair_project().getName();
        if(!TextUtil.isEmpty(type)){
            holder.setText(R.id.tv_type,type);
        }
        
        
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getData(false,page);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page = page +1;
        getData(false,page);
    }

    @Override
    public void onClick(View view) {
        
    }
    
    @OnClick(R.id.tv_hebinfukuang)
    public void pay(){
        
        ArrayList<AppointmentEntity.DataBean.AppointBean> datas = myAppointmentAdapter.getSelects();
        if(datas!=null&&datas.size()>0){
            Intent intent = new Intent(getActivity(), MergePaymentsActivity.class);
            String wa_ids = "";
            intent.putExtra("wa_ids",wa_ids);
            intent.putExtra("data",myAppointmentAdapter.getSelect());
            getActivity().startActivity(intent);
        }else {
            ToastUtil.toastShortNegative("请先选择预约单");
        }
        
    }
    
    
    
    @Subscribe
    public void onEventMainThread(YEventBuses.Event event){
        if(event.is(MyAppointmentAdapter.SELECT)){
            if(checkBox.isChecked()){
                isAll = true;
            }else {
                isAll = false;
            }
            checkBox.setChecked(false);
            tv_orderNum.setText("合计："+myAppointmentAdapter.getSelect().size()+"个预约单");
        }else if(event.is(StrConst.UMENG_PUSH)){
            String params = (String)event.getParams(0);
            int status = Integer.valueOf(params);
            switch (status){
                case 1:
                    page = 1;
                    getData(false,page);
                    break;
                case 2:
                    page = 1;
                    getData(false,page);
                    break;
                case 3:
                    page = 1;
                    getData(false,page);
                    break;
                case 4:
                    page = 1;
                    getData(false,page);
                    break;
                case 5:
                    
                    break;
            }
        }else if(event.is(MyAppointmentAdapter.CANCEL)){
            if(status==0){
                page = 1;
                LogUtil.i("mylog","取消成功重新请求");
                getData(true,page);
            }
        }else if(event.is(MergePaymentsActivity.DELETE)){
            if(status==2){
                page = 1;
                getData(true,page);
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        YEventBuses.unregister(this);
    }
}
